package ch01.observer;

import javafx.collections.ObservableArray;

import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by zc on 2016/10/25.
 */
public class ObserverQueue extends Observable implements Observer, Runnable {
    private LinkedList queue = new LinkedList();

    @Override
    public void run() {
        while(true){
            Object object = get();
            setChanged();
            notifyObservers(object);
        }
    }

    public void attachObservable(Observable watched){
        watched.addObserver(this);
    }

    @Override
    public void update(Observable o, Object arg) {
        queue.add(arg);
    }

    public synchronized Object get(){
        try {
            while(queue.size() == 0){
                this.wait();
            }
        } catch (InterruptedException ex){
            ex.printStackTrace();
        }
        return queue.removeFirst();
    }
}
